package net.tngou.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;








import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;









import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.tngou.tnfs.HttpConfig;




/**

 *  图片操作

 * @author tngou

 *

 */
public class ImgUtil {
	private static final Logger log= LoggerFactory.getLogger(ImgUtil .class);

	
	/**

	 * 下载图片

	 * @param imgUrl 图片地址

	 * @param savePath 保存地址

	 * @param saveUrl 保存的URL地址

	 * @return

	 */
	public static String DownImg(String imgUrl,String savePath ,String name) {
	
		//取得今天时间
		  HttpConfig httpConfig = HttpConfig.getInstance();
			File dirFile = new File(httpConfig.getTnfspath()+File.separator+"img"+File.separator+savePath); //如果今天的目录存储就创建

			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			
		 try {
					
				URL ImgUrl= new URL(imgUrl);
				
					if(StringUtils.isEmpty(name)) name=DigestMD.MD5(imgUrl);
					name = name +".jpg" ;				
					//取得今天时间			

					File fileDest = new File(dirFile, name);
			
//					FileOutputStream fos = new FileOutputStream(fileDest);

					//FileUtils.copyFile(imgData, fos);

				
					
					boolean r = _copyURLToFile(ImgUrl, fileDest, httpConfig);
					if(!r) return null;
					//IOUtils.copy(imgData, fos);	

					 if(!fileDest.isFile())return null;
					 BufferedImage bufferedImage = ImageIO.read(fileDest);
					 int w = bufferedImage.getWidth();
					 int h = bufferedImage.getHeight();
					 if(w<httpConfig.getMinwidth()&&h<httpConfig.getMinheight())  //小图标进行过滤  如：最小 80x60

					 {
						 fileDest.delete();
						 return null;
					 }
					 
//					 savePath  += name;
//				

		   return httpConfig.getImgurl()+"/"+savePath+"/"+name;
	   } catch (Exception e) {
		   log.error("现在图片地址-{}-出错",imgUrl);
		   e.printStackTrace();
		   return null;
		}
		
		
		
	}
	
	

	/**

	 * 取全部图片

	 * @return

	 */
	public static Set<String> Images(URL url,String filtersuffix) {
			
		Set<String> list = new HashSet<String>();
		//从词条中取得一张图片

				Document doc= HttpUtil.get(url.toString());
				Elements imgs = doc.select("img");
				for(int i=0;i<imgs.size();i++){
					  Element img = imgs.get(i);
						String src = img.attr("abs:src");
						if(filtersuffix!=null)src=StringUtils.removeEnd(src, filtersuffix);
						list.add(src);//	

				}
		return list;
		
	}
	
	private static boolean _copyURLToFile( URL imgUrl, File fileDest , HttpConfig httpConfig)
	{
		
		String imgurl = imgUrl.toString();
		try {
		HttpURLConnection cnx = (HttpURLConnection)imgUrl.openConnection();
		cnx.setAllowUserInteraction(false);         
		cnx.setDoOutput(true);
		cnx.addRequestProperty("Cache-Control", "no-cache");
		cnx.addRequestProperty("User-Agent", httpConfig.getUserAgent());
		cnx.addRequestProperty("Referer", imgurl.substring(0, imgurl.indexOf('/', imgurl.indexOf('.'))+1));
		cnx.setConnectTimeout(httpConfig.getTimeout());
		cnx.setReadTimeout(httpConfig.getTimeout());
			cnx.connect();
		
		if(cnx.getResponseCode() == HttpURLConnection.HTTP_OK)
		{
			InputStream imgData = cnx.getInputStream();
		
			FileOutputStream fos = new FileOutputStream(fileDest);

			IOUtils.copy(imgData, fos);
			
			IOUtils.closeQuietly(imgData);
			IOUtils.closeQuietly(fos);	

		}else
		{
			return false;
		}
		
		} catch (IOException e) {
			
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public static void  Drop(String src) {
		
		HttpConfig config=HttpConfig.getInstance();		
		File file = new File(config.getTnfspath()+"\\img"+src);
		file.delete();
		
	}
	
	
	public static void main(String[] args) throws IOException {
		File fileDest=new File("D:/123.jpg");
		URL ImgUrl=new URL("http://www.yi18.net/img/news/20141128165650_647.jpg");
		System.err.println(ImgUrl.toString());
		//DownImg("http://www.yi18.net/img/news/20141128165650_647.jpg", "D:/test/", "tsts", "");

	}
	
}
